const cloud = require("wx-server-sdk");

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

const db = cloud.database();
const _ = db.command;

const queryRegistrantCheckInInfo = async event => {
  const groupID = event && event.groupID;
  if (!groupID) {
    return { success: false, error: "缺少活动分组ID" };
  }

  try {
    const registrationRes = await db
      .collection("Group_Registration_Information")
      .where({ GroupID: groupID })
      .field({
        OpenID: 1,
        IsCheckedIn: 1,
        IsCheckedOut: 1,
        CheckInTime: 1,
        CheckOutTime: 1
      })
      .get();

    const registrationRecords = registrationRes.data || [];
    const openIDs = Array.from(new Set(registrationRecords.map(item => item.OpenID)));

    let profileMap = new Map();
    if (openIDs.length > 0) {
      const profileRes = await db
        .collection("User_Profile")
        .where({ OpenID: _.in(openIDs) })
        .field({
          OpenID: 1,
          Name: 1,
          Nickname: 1,
          StudentID: 1
        })
        .get();

      profileMap = new Map(
        (profileRes.data || []).map(profile => [profile.OpenID, profile])
      );
    }

    const checkInRegistrants = [];
    const checkOutRegistrants = [];

    registrationRecords.forEach(record => {
      const profile = profileMap.get(record.OpenID) || {};
      if (record.CheckInTime) {
        checkInRegistrants.push({
          openID: record.OpenID,
          name: profile.Nickname || profile.Name || "",
          studentID: profile.StudentID || "",
          checkInTime: record.CheckInTime
        });
      }
      if (record.CheckOutTime) {
        checkOutRegistrants.push({
          openID: record.OpenID,
          name: profile.Nickname || profile.Name || "",
          studentID: profile.StudentID || "",
          checkOutTime: record.CheckOutTime
        });
      }
    });

    return {
      success: true,
      checkInRegistrants,
      checkOutRegistrants
    };
  } catch (error) {
    console.error("queryRegistrantCheckInInfo error", error);
    return {
      success: false,
      error: error.message || "查询签到记录失败"
    };
  }
};

exports.main = async event => {
  return queryRegistrantCheckInInfo(event || {});
};
